//
//  selectLabelViewController.m
//  SouthChina
//
//  Created by zorro on 15/7/3.
//  Copyright (c) 2015年 科创. All rights reserved.
//

#import "selectLabelViewController.h"
#import "DataDictDao.h"
#import "selectMemberTableViewCell.h"
#import "PersonalInforViewController.h"
#include "GroupInfoViewController.h"

@interface selectLabelViewController ()<UITableViewDataSource,UITableViewDelegate>

{
    NSArray * allLabeData;
}

@end

@implementation selectLabelViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    if([_sLableType isEqualToString:GROUP_LABLE])
        [self addTitleBarWithBackBtn:@"选择群标签" needReturn:TRUE];
    else
        [self addTitleBarWithBackBtn:@"选择个人标签" needReturn:TRUE];
   UIView * viewBody = [[[NSBundle mainBundle] loadNibNamed:@"selectLabelViewBody" owner:self options:nil] objectAtIndex:0];
    
    viewBody.frame = (CGRect){0, TITLE_BAR_HEGIHT+YNEW,SCREEN_WIDTH, SCREEN_HEIGHT-TITLE_BAR_HEGIHT-YNEW};
    [self.view addSubview:viewBody];
    
    _tabLable.delegate = self;
    _tabLable.dataSource = self;
    _tabLable.bounces=NO;
    
    //标题栏上显示完成按钮
    UIButton *confirmBtn = [[UIButton alloc] initWithFrame:CGRectMake(260, self.titlebar.frame.origin.y+20, 50, 40)];
    [confirmBtn addTarget:self action:@selector(confirmBtn:) forControlEvents:UIControlEventTouchUpInside];
    [confirmBtn setTitle:@"确定" forState:UIControlStateNormal];
     confirmBtn.titleLabel.font = [UIFont systemFontOfSize:17.0f];
    [self.titlebar addSubview:confirmBtn];
    
    
    [self refreshTableView:@""];
    
    [self setExtraCellLineHidden:_tabLable];
    
}

-(void)confirmBtn:(id)sender
{
    if([_sLableType isEqualToString:GROUP_LABLE])//创建群时选择群标签，直接回到上一级
    {
        [self btnBack];
    }
    else if([_sLableType isEqualToString:PERSON_LABLE]) //个人群标签
    {
        NSEnumerator *enumeratorLable = [_selectedLable objectEnumerator];
        NSMutableString *idsLable = [[NSMutableString alloc] initWithString:@""];
        for (DataDict *cid in enumeratorLable) {
            [idsLable insertString:[NSString stringWithFormat:@"%@,",cid.dictdataValue] atIndex:0];}
        NSDictionary *map = @{@"userTags":idsLable};
        [DE serverCall:@"updateUserInfo" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
            if(success)
            {
                [DE setGlobalVar:LOGIN_USER_TAGS value:idsLable];
                //回退到上一级页面
                [self.navigationController popViewControllerAnimated:YES];
                //得到最上面那个viewcontroller
                PersonalInforViewController *PersonalInfoviewC = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count-1)];
                [PersonalInfoviewC showAlerHUD:@"修改个人标签成功"];
            }
            else{
                [self.navigationController popViewControllerAnimated:YES];
                //得到最上面那个viewcontroller
                PersonalInforViewController *PersonalInfoviewC = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count-1)];
                [PersonalInfoviewC showAlerHUD:@"修改个人标签失败"];
                
            }
        }];
    }
    else //重置群标签
    {
        NSEnumerator *enumeratorLable = [_selectedLable objectEnumerator];
        NSMutableString *idsLable = [[NSMutableString alloc] initWithString:@""];
        for (DataDict *cid in enumeratorLable) {
            [idsLable insertString:[NSString stringWithFormat:@"%@,",cid.dictdataId] atIndex:0];
        }
        if ([idsLable isEqualToString:@""]) {
            NSLog(@"重置标签为空，，，，，，，，，，，");
             [idsLable insertString:[NSString stringWithFormat:@"%@,",@""] atIndex:0];
        }
        NSLog(@"idsLable,,,,%@",idsLable);
        
        NSDictionary *map = @{@"groupId":_groupId,@"groupTags":idsLable};
        [DE serverCall:@"modifyGroupTags" params:map callback:^(BOOL success, int code, NSString *desc, NSDictionary *data,NSDictionary*param) {
            if(success)
            {
                //回退到上一级页面
                [self.navigationController popViewControllerAnimated:YES];
                //得到最上面那个viewcontroller
                 GroupInfoViewController *GroupInfoviewC = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count-1)];
                [GroupInfoviewC showAlerHUD:@"修改群标签成功"];
            }
            else{
                [self.navigationController popViewControllerAnimated:YES];
                //得到最上面那个viewcontroller
                GroupInfoViewController *GroupInfoviewC = [self.navigationController.viewControllers objectAtIndex:(self.navigationController.viewControllers.count-1)];
                [GroupInfoviewC showAlerHUD:@"修改群标签失败"];
                
            }
        }];
    }
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/
/*
- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    
    [self refreshTableView:searchText];
    
}

// called when cancel button pressed
- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar{
    
   [self searchBar:searchBar textDidChange:@""];
    
}

*/

-(void) refreshTableView:(NSString *)searchText
{
    NSString *sql = [NSString stringWithFormat:@"where dicttypeId ='8' and dictdataValue like '%%%@%%'",searchText];
    allLabeData = [DataDictDao queryDataDict:sql];
    [_tabLable reloadData];
}


- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return allLabeData.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   
    static NSString * CellIdentifier = @"selectMemberTableViewCell";
    selectMemberTableViewCell *cell=[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if(!cell)
    {
        cell = [[[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil] objectAtIndex:0];
    }
    
    DataDict *dict =[allLabeData objectAtIndex:indexPath.row];
    
    [cell setContactSelected:[self containsDataDict:_selectedLable dict:dict]];
    [cell setDataDictCell:dict];
    cell.detailLabel.hidden = YES;
    
    return cell;
}

- (BOOL)containsDataDict:(NSMutableSet*) set dict:(DataDict *)dict
{
    for (DataDict * i   in  set)
    {
        if ([i.dictdataValue isEqualToString:dict.dictdataValue]) {
            return YES;
        }
    }
    return NO;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 50;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    //选种的单元格信息
    DataDict *dict =[allLabeData objectAtIndex:indexPath.row];

    
    BOOL isFind = NO;
    for (DataDict * i   in  _selectedLable)
    {
        if ([i.dictdataValue isEqualToString:dict.dictdataValue]) {
            [_selectedLable removeObject:i];
            isFind = YES;
            break;
        }
    }
    
    if (!isFind) {
        [_selectedLable addObject:dict];
    }
    
    NSArray *indexArray=[NSArray arrayWithObject:indexPath];
    [tableView reloadRowsAtIndexPaths:indexArray withRowAnimation:UITableViewRowAnimationAutomatic];
}



@end
